package com.leetcode;

import com.study.common.ListNode;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-17 11:20
 * @version: 1.0
 * @description: 相交链表
 * 给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点，返回 null 。
 **/
public class IntersectLink {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1, null);
        ListNode node2 = new ListNode(2, node1);
        ListNode node3 = new ListNode(3, node2);
        ListNode node4 = new ListNode(4, node3);
        ListNode headB = new ListNode(5, node4);
        ListNode node6 = new ListNode(6, node2);
        ListNode node7 = new ListNode(7, node6);
        ListNode headA = new ListNode(8, node7);
        ListNode node = intersect(headA,headB);
    }

    private static ListNode intersect(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode p1 = headA,p2 = headB;
        while (p1 != p2){
            p1 = p1 == null ? headB : p1.next;
            p2 = p2 == null ? headA : p2.next;
        }
        return p1;
    }
}
